package com.tinem.platform.web.gateway.filter;

import com.tinem.platform.module.pojo.co.GatewayHeadName;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.addOriginalRequestUrl;

/**
 * @author fengzhihao
 * @version v1
 * @program: platform
 * @className DiscoveryRewritePathGatewayFilterFactory
 * @description TODO
 * @site 
 * @company 
 * @create 2020-06-23 18:03
 */
@Component
public class DiscoveryRewritePathGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> {


    @Override
    public GatewayFilter apply(Object config) {
        return (exchange, chain) -> {
            ServerHttpRequest req = exchange.getRequest();
            addOriginalRequestUrl(exchange, req.getURI());
            String newPath = req.getHeaders().getFirst(GatewayHeadName.X_PLATFORM_GATEWAY_REQ_METHOD);
            ServerHttpRequest request = req.mutate()
                    .path(newPath).build();
            exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, request.getURI());

            return chain.filter(exchange.mutate().request(request).build());
        };
    }
}
